<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>修改通讯录</title>

    <!-- bootstrap -->
    <link rel="stylesheet" href="./assets/css/bootstrap.min.css" />

    <!-- animate.css -->
    <link rel="stylesheet" href="./assets/css/animate.min.css" />

    <!-- MUI -->
    <link rel="stylesheet" href="./assets/plugins/mui/css/mui.min.css">

    <!-- 引入bootstrapValidator表单验证插件 -->
    <link rel="stylesheet" href="./assets/plugins/bootstrap-validator/bootstrapValidator.min.css">

    <!-- 城市组件 -->
    <link rel="stylesheet" href="./assets/plugins/city-picker/city-picker.css">

    <!-- 重置样式 -->
    <link rel="stylesheet" href="./assets/css/reset.css" />

    <!-- 公共样式 -->
    <link rel="stylesheet" href="./assets/css/common.css" />

    <!-- 页面独立的 -->
    <link rel="stylesheet" href="./assets/css/ContactAdd.css" />
</head>

<body>
    <!-- 修改通讯录 -->
    <div class="info">
        <h3 class="title wow fadeInUp">修改通讯录</h3>

        <p class="desc wow fadeInUp" data-wow-delay="200ms" style="color: #fff;">
            您可在本页录入您的联系信息，录入成功后名片将会出现在首页。如需修改首页名片信息，也请新建录入，将会自动替换原有名片。
        </p>
    </div>

    <form class="contact wow fadeInUp" data-wow-delay="300ms" method="post">
        <div class="form-group">
            <label for="nickname">姓名</label>
            <input type="text" class="form-control" id="nickname" name="nickname" placeholder="请输入姓名" required />
        </div>

        <div class="form-group">
            <label for="mobile">手机号码</label>
            <input type="text" class="form-control" id="mobile" name="mobile" placeholder="请输入手机号码" required />
        </div>

        <div class="form-group">
            <label for="gender">性别</label>
            <select class="form-control" id="gender" name="gender">
                <option value="">请选择</option>
                <option value="0">保密</option>
                <option value="1">男</option>
                <option value="2">女</option>
            </select>
        </div>

        <div class="form-group">
            <label for="type">分类</label>
            <select class="form-control" name="typeid" id="type">
                <option value="">请选择</option>
            </select>
        </div>

        <div class="form-group" style="position: relative;">
            <label for="email">城市</label>
            <div class='control-relative'>
                <input id="city" class="form-control" data-toggle="city-picker" type="text" />
            </div>
        </div>

        <div class="form-group">
            <label for="remark">备注</label>
            <input type="text" class="form-control" id="remark" name="remark" placeholder="请输入备注" />
        </div>

        <div class="action">
            <button class="btn" type="submit">提交</button>
        </div>
    </form>
</body>

</html>
<!-- jquery  -->
<script src="./assets/js/jquery.min.js"></script>

<!-- bootstrap -->
<script src="./assets/js/bootstrap.min.js"></script>

<!-- wow.js -->
<script src="./assets/js/wow.min.js"></script>

<!-- MUI -->
<script src="./assets/plugins/mui/js/mui.min.js"></script>

<!-- 引入bootstrapValidator表单验证插件 -->
<script src="./assets/plugins/bootstrap-validator/bootstrapValidator.min.js"></script>

<!-- axios请求 -->
<script src="./assets/plugins/axios/axios.js"></script>
<script src="./assets/plugins/axios/request.js"></script>

<!-- 城市组件 -->
<script src="./assets/plugins/city-picker/city-picker.data.min.js"></script>
<script src="./assets/plugins/city-picker/city-picker.min.js"></script>

<!-- cookie -->
<script src="./assets/plugins/cookie.js"></script>

<!-- 校验用户是否登陆 -->
<script src="./assets/plugins/helper.js"></script>

<script>
    //实例化wow.js
    new WOW().init();

    // 获取下拉分类列表
    (async function () {
        let result = await POST({ url: 'card/card/type' })
        if (result.code == 1) {
            result.data.forEach((item) => {
                let str = `
                    <option value="${item.id}">${item.name}</option>
                `
                $("#type").append(str)
            })
        }
    })();

    let Business = cookie.get('Business') ? JSON.parse(cookie.get('Business')) : "{}";
    // console.log(Business);



    // 获取url地址的参数cardid
    // URL 接口的 searchParams 属性返回一个 URLSearchParams 对象，这个对象包含当前 URL 中解码后的 GET 查询参数。
    let params = new URL(document.location).searchParams;
    let cardid = params.get("cardid");

    // 请求回写
    (async function () {
        let result = await POST({
            url: 'card/card/check',
            params: {
                businessid: Business.id,
                cardid: cardid
            }
        })
        console.log(result.data);
        // 回写，如果提交成功，名字上传到result.data
        // 显示到输入框上
        if (result.code == 1) {
            $("#nickname").val(result.data.nickname)
            $("#mobile").val(result.data.mobile)
            $("#gender").val(result.data.gender)
            $("#type").val(result.data.typeid)
            $("#remark").val(result.data.remark)

            // 销毁现有的 citypicker 实例
            $('#city').data('citypicker').destroy();
            let city = result.data.region_text.split("-");
            if (['北京', '天津', '上海', '重庆'].includes(city[0])) {
                // 设置新的数据属性
                $('#city').data('province', city[1]);
                $('#city').data('city', city[1]);
                $('#city').data('district', city[2]);
                // 重新初始化 citypicker
                $('#city').citypicker();
            } else {
                $('#city').data('province', city[0]);
                $('#city').data('city', city[1]);
                $('#city').data('district', city[2]);
                $('#city').citypicker();
            }
        }
    })();

    // 对form元素绑定校验规则
    $("form").bootstrapValidator({
        // 图标
        feedbackIcons: {
            valid: 'glyphicon glyphicon-ok',
            invalid: 'glyphicon glyphicon-remove',
            validating: 'glyphicon glyphicon-refresh'
        },
        // 字段
        fields: {
            nickname: {
                validators: {
                    notEmpty: { // 非空校验
                        message: '昵称不能为空!'
                    },
                }
            },
            gender: {
                validators: {
                    notEmpty: { // 非空校验
                        message: '性别不能为空!'
                    }
                }
            },
            address: {
                validators: {
                    notEmpty: { // 非空校验
                        message: '地址不能为空!'
                    },
                    stringLength: { // 长度校验
                        min: 4,
                        max: 50,
                        message: '地址长度在%s~%s范围内！'
                    }
                }
            }
        }
    }).on('success.form.bv', function (e) {
        e.preventDefault();
    })



    $("form").submit(async function (e) {
        // 新建对象，接收表单字段
        let data = {
            cardid: cardid,
            gender: $("#gender").value,
            businessid: Business.id
        }
        // serializeArray()收集form所有表单字段，每个字段包含name和value属性
        var fields = $("form").serializeArray();
        $.each(fields, function (i, field) {
            data[field.name] = field.value
        });
        console.log(data);

        // 获取地址行政区域代码，顺序区>市>省
        var citypicker = $("#city").data("citypicker");
        var code;

        // 检查是否为直辖市，直辖市的编码直接用区的编码
        if (['北京市', '天津市', '上海市', '重庆市'].includes(citypicker.getCode("city"))) {
            code = citypicker.getCode("district") || citypicker.getCode("city");
        } else {
            // 原逻辑获取编码
            // 注意这里直接获取区编码，如果没有区编码，则获取市编码，如果市编码也没有，则获取省编码
            code = citypicker.getCode("district") || citypicker.getCode("city") || citypicker.getCode("province");
        }
        data.region = code;
        //   console.log(data.region);


        let result = await POST({
            url: 'card/card/edit',
            params: data
        })
        if (result.code == 1) {
            mui.toast(result.msg);
            setTimeout(() => {
                location.href = 'index.html'
            }, 1000)
        } else {
            mui.toast(result.msg);
            $('form').data('bootstrapValidator').resetForm(true); // 重置校验
        }


    })
</script>